import { Renderer } from "@k8slens/extensions";
import React from "react";
import { observable } from "mobx";
import { observer } from "mobx-react";
import tls, { PeerCertificate } from "tls";
import net from "net";
import {
    ValidatingWebhookConfiguration,
    ValidatingWebhookConfigurationApi,
} from "../webhooks-objects/ValidatingWebhookConfiguration";

import * as x509 from "@peculiar/x509";
import moment from "moment";

@observer
export class ValidatingWebhookConfigurationCA extends React.Component<
    Renderer.Component.KubeObjectDetailsProps<ValidatingWebhookConfiguration>
> {
    
    render() {
        const webhooks: any[] = this.props.object["webhooks"] || [];
        return <div>
            <Renderer.Component.DrawerTitle>
                ValidatingWebhookConfiguration CA
            </Renderer.Component.DrawerTitle>
            {
                webhooks.map(webhook => {
                    return this.renderWebhook(webhook)
                })
            }
        </div>;
    }

    renderWebhook(webhook: any) {
        const certificates: any[] = [];
        const certificateString = Buffer.from(
            webhook["clientConfig"]["caBundle"],
            "base64"
        ).toString("ascii");

        if (!certificateString.startsWith("-----BEGIN CERTIFICATE-----")) {
            return <div>Invalid certificate</div>
        }
        try {
            const cert = new x509.X509Certificate(certificateString)

            certificates.push(
                <div>
                    <Renderer.Component.DrawerItem name="Subject">
                        {cert.subject}
                    </Renderer.Component.DrawerItem>
                    <Renderer.Component.DrawerItem name="SignatureAlgorithm">
                        {cert.signatureAlgorithm.name +" "+cert.signatureAlgorithm.hash.name}
                    </Renderer.Component.DrawerItem>
                    <Renderer.Component.DrawerItem name="Issuer">
                        {cert.issuer}
                    </Renderer.Component.DrawerItem>
                    <Renderer.Component.DrawerItem name="Not before">
                        {moment(cert.notBefore).format()}
                    </Renderer.Component.DrawerItem>
                    <Renderer.Component.DrawerItem name="Expires">
                        {moment(cert.notAfter).format()}
                    </Renderer.Component.DrawerItem>
                </div>
            );
        } catch (e) {
            console.error(e);
        }


        return <div>
            <Renderer.Component.DrawerTitle>
                {webhook["name"]}
            </Renderer.Component.DrawerTitle>
            { certificates}
        </div>

    }
}
